package com.cooba.activitys.Living;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cooba.R;
import com.cooba.adapter.LivingDetailAdapter;
import com.cooba.bean.LivingDetailBean;
import com.cooba.bean.MyLivingBean;
import com.cooba.mqtt.MqttBroker;
import com.cooba.pullTorefresh.PullToRefreshBase;
import com.cooba.pullTorefresh.PullToRefreshListView;
import com.cooba.upload.CustomMultipartEntity;
import com.cooba.utils.BitmapZipUtil;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.cooba.views.ProgressImageView;
import com.cooba.views.loadview.LoadViewHelper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import me.nereo.multi_image_selector.MultiImageSelector;

public class MyLivingDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private static final int REQUEST_IMAGE = 0;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;
    protected static final int REQUEST_STORAGE_WRITE_ACCESS_PERMISSION = 102;
    private static final int REQUEST_TEXT = 1;

    private ArrayList<LivingDetailBean.LivingDetailContent> myLivingList;
    private ScrollView my_living__detail_sv;
    private ImageButton my_living_detail_back_ib;
    private ImageView my_living_detail_add_iv;
    private RelativeLayout my_living__detail_add_rl;
    private ImageView my_living_detail_add_text_iv;
    private ImageView my_living_detail_add_image_iv;
    private LinearLayout my_living_detail_add_layout_ll;
    private PullToRefreshListView rListView;
    private LivingDetailAdapter mAdapter;
    private PopupWindow popWindow;
    private boolean isOpen = false;
    private MyLivingBean.LiveListBean mylivingbeaninfo;
    private LoadViewHelper helper;
    private boolean mIsFirstLoad = true;
    private HttpUtils httpUtils;
    private RequestParams params;
    private String next_key = "0";
    private LivingDetailBean livingdetailbean;
    private HttpHandler<String> handler;
    private LayoutInflater li;
    private ProgressImageView imageView;
    private int i = 0;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private ArrayList<File> fileList = new ArrayList<>();
    private HttpMultipartPost post;
    private StringBuilder sburl;
    private Dialog dialog;
    private TextView upload_image_progress_tv;
    private StringBuilder sbwh;
    private LivingDetailBean.LivingDetailContent livingdetailcontentbean;
    private LinearLayout my_living__detail_no_data_ll;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_living_detail);
        mylivingbeaninfo = (MyLivingBean.LiveListBean) getIntent().getSerializableExtra("mylivingbean");
        initView();
        initHeadView();
    }

    private void initHeadView() {
        View headerView = View.inflate(this, R.layout.living_head_view_new, null);
        View footerView = View.inflate(this, R.layout.footer_view_layout, null);
        TextView textView = (TextView) headerView.findViewById(R.id.living_head_view_big_title);
        my_living__detail_no_data_ll= (LinearLayout) headerView.findViewById(R.id.my_living__detail_no_data_ll);
        textView.setText(mylivingbeaninfo.getName());
        final ImageView imageView = (ImageView) headerView.findViewById(R.id.living_head_view_image);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        BitmapUtils bitmapUtils = new BitmapUtils(this);
        /**
         * 设置默认的图片展现、加载失败的图片展现
         */
        bitmapUtils.configDefaultLoadingImage(R.mipmap.default_icon1);
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.default_icon1);
        bitmapUtils.display(imageView, mylivingbeaninfo.getPic());
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int) (width * 0.56);
        LinearLayout.LayoutParams laParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
        laParams.width = width;
        laParams.height = height;
        imageView.setLayoutParams(laParams);
        my_living_detail_add_text_iv = (ImageView) headerView.findViewById(R.id.my_living_detail_add_text_iv);
        my_living_detail_add_image_iv = (ImageView) headerView.findViewById(R.id.my_living_detail_add_image_iv);
        my_living__detail_add_rl = (RelativeLayout) headerView.findViewById(R.id.my_living__detail_add_rl);
        my_living_detail_add_iv = (ImageView) headerView.findViewById(R.id.my_living_detail_add_iv);
        my_living_detail_add_layout_ll = (LinearLayout) headerView.findViewById(R.id.my_living_detail_add_layout_ll);
        my_living_detail_add_image_iv.setOnClickListener(this);
        my_living_detail_add_text_iv.setOnClickListener(this);
        my_living_detail_add_layout_ll.setVisibility(View.GONE);
        my_living_detail_add_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isOpen) {
                    my_living_detail_add_layout_ll.setAnimation(AnimationUtils.makeInAnimation(MyLivingDetailActivity.this, true));
                    my_living_detail_add_layout_ll.setVisibility(View.VISIBLE);
                    isOpen = true;
                } else {
                    my_living_detail_add_layout_ll.setAnimation(AnimationUtils.makeOutAnimation(MyLivingDetailActivity.this, false));
                    my_living_detail_add_layout_ll.setVisibility(View.GONE);
                    isOpen = false;
                }
            }
        });
        rListView.getRefreshableView().addHeaderView(headerView);
        //rListView.getRefreshableView().addFooterView(footerView);
        getMylivingDetail(true);
    }

    private void initView() {
        myLivingList = new ArrayList<>();
        my_living_detail_back_ib = (ImageButton) findViewById(R.id.my_living_detail_back_ib);
        my_living_detail_back_ib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        initPullTorefresh();
        helper = Utils.initLoadViewHelper(rListView);
    }

    private void initPullTorefresh() {
        rListView = (PullToRefreshListView) findViewById(R.id.my_living_detail_lv);
        rListView.setPullRefreshEnabled(false);
        rListView.setPullLoadEnabled(true);  //上拉加载，屏蔽
        rListView.setScrollLoadEnabled(true); //设置滚动加载可用
        rListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {//下拉刷新

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {//上拉加载
                getMylivingDetail(false);
            }
        });
        rListView.getRefreshableView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position > 0) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MyLivingDetailActivity.this);
                    //builder.setTitle("title");
                    builder.setMessage("是否删除?");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String id = mAdapter.getItem(position - 1).getId();
                            deleteData(id);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.show();
                }
                return false;
            }
        });

        mAdapter = new LivingDetailAdapter(this, myLivingList);
        rListView.getRefreshableView().setAdapter(mAdapter);
    }

    private void deleteData(String id) {
        httpUtils=new HttpUtils();
        params=new RequestParams();
        params.addBodyParameter("id", id);
        httpUtils.send(HttpRequest.HttpMethod.POST, ServerURL.httpUrl + ServerURL.deletemylivingcontent,params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei","删除直播内容成功"+responseInfo.result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String status = jsonObject.get("status").toString();
                    if (status.equals("1")) {
                        getMylivingDetail(true);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei","删除直播内容失败"+msg);
            }
        });
    }

    private void getMylivingDetail(final boolean isFirst) {
//        if (mIsFirstLoad) {
//            helper.showLoading("正在加载...");
//        }
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id = SharedPreferencesUtil.getData(this, "login_id", "");
        //params.addBodyParameter("user_id", login_id);
        params.addBodyParameter("liveId", mylivingbeaninfo.getId());
        if (isFirst) {
            next_key = "0";
        }
        params.addBodyParameter("next_key", next_key);
        params.addBodyParameter("page_size", "10");
        String urllivingcontentlist = ServerURL.httpUrl + ServerURL.livingcontentlist;
        handler = httpUtils.send(HttpRequest.HttpMethod.POST, urllivingcontentlist, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取直播详情列表失败");
                Toast.makeText(MyLivingDetailActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
                rListView.setHasMoreData(false);
                rListView.onPullDownRefreshComplete();
                rListView.onPullUpRefreshComplete();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取直播详情列表成功" + responseInfo.result);
                try {
                    livingdetailbean = new Gson().fromJson(responseInfo.result, LivingDetailBean.class);
                    if (livingdetailbean.getContentList() != null && livingdetailbean.getContentList().size() > 0) {
                        if (isFirst) {
                            mAdapter.setList(livingdetailbean.getContentList());
                        } else {
                            mAdapter.addMoreData(livingdetailbean.getContentList());
                        }
                        if (livingdetailbean.getNext_key() == null) {
                            next_key = String.valueOf(livingdetailbean.getContentList().size() + Integer.parseInt(next_key));
                        } else {
                            next_key = livingdetailbean.getNext_key();
                        }
                        if (livingdetailbean.getContentList().size() < 10) {
                            rListView.setHasMoreData(false);
                        }
//                        mIsFirstLoad = false;
//                        helper.restore();
                    } else {
                        if (isFirst) {
                            rListView.setHasMoreData(false);
                            //my_living__detail_no_data_ll.setVisibility(View.VISIBLE);
//                            helper.restore();
                            //helper.showEmpty("暂时没有数据", "重新加载", false, null);
                        } else {
                            Toast.makeText(MyLivingDetailActivity.this, "没有更多数据啦", Toast.LENGTH_SHORT).show();
                        }
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                } finally {

                    rListView.onPullDownRefreshComplete();
                    rListView.onPullUpRefreshComplete();

                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.my_living_detail_add_text_iv:
//                Intent intent = new Intent(MyLivingDetailActivity.this, LivingContentAddActivity.class);
//                intent.putExtra("live_id", mylivingbeaninfo.getId());
//                startActivityForResult(intent, REQUEST_TEXT);
                //Intent intent = new Intent(MyLivingDetailActivity.this, LivingContentAddTitleActivity.class);
                Intent intent = new Intent(MyLivingDetailActivity.this, LivingContentAddNew1Activity.class);
                intent.putExtra("live_id", mylivingbeaninfo.getId());
                startActivityForResult(intent, REQUEST_TEXT);
                break;
            case R.id.my_living_detail_add_image_iv:
                pickImage();
                //sendMessage();
                break;
            default:
                break;
        }
    }

    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        }
        {
            MultiImageSelector.create(MyLivingDetailActivity.this)
                    .showCamera(true) // 是否显示相机. 默认为显示
                    .count(3) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
                    .multi() // 多选模式, 默认模式;
                    .start(MyLivingDetailActivity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MyLivingDetailActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath.clear();
                mSelectPath = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                StringBuilder sb = new StringBuilder();
                for (String p : mSelectPath) {
                    sb.append(p);
                    sb.append("\n");
                }
                //Toast.makeText(MyLivingDetailActivity.this, sb.toString(), Toast.LENGTH_SHORT).show();
                showUploadDialog();
            }
        } else if (requestCode == REQUEST_TEXT) {
            if (resultCode == RESULT_OK) {
//                livingdetailcontentbean= (LivingDetailBean.LivingDetailContent) data.getSerializableExtra("livingdetailcontentbean");
//                livingdetailbean.getContentList().add(0,livingdetailcontentbean);
//                mAdapter.setList(livingdetailbean.getContentList());
                getMylivingDetail(true);
            }
        }
    }

    private void showUploadDialog() {
        dialog = new Dialog(this);
        li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View v = li.inflate(R.layout.dialog_upload_image, null);
        android.view.Window window = dialog.getWindow();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(v);
        dialog.setCanceledOnTouchOutside(false);
        //window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.setGravity(Gravity.CENTER);
        dialog.show();
        imageView = (ProgressImageView) v.findViewById(R.id.upload_image_progress_iv);
        upload_image_progress_tv = (TextView) v.findViewById(R.id.upload_image_progress_tv);
        TextView cancel = (TextView) v.findViewById(R.id.upload_image_progress_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        fileList.clear();
        i = 0;
        for (int i = 0; i < mSelectPath.size(); i++) {
            File file = BitmapZipUtil.scal(mSelectPath.get(i),MyLivingDetailActivity.this);

            fileList.add(file);
        }
        Bitmap bitmap = BitmapFactory.decodeFile(fileList.get(0).getPath());
        imageView.setImageBitmap(bitmap);
        sburl = new StringBuilder();
        upload();
    }

    private void upload() {
        post = new HttpMultipartPost(MyLivingDetailActivity.this, fileList.get(i).getPath(), ServerURL.httpUrl + ServerURL.uploadImg);
        post.execute();
    }

    class HttpMultipartPost extends AsyncTask<String, Integer, String> {

        private Context context;
        private String filePath;
        //private ProgressDialog pd;
        private long totalSize;
        private String requestUrl;

        public HttpMultipartPost(Context context, String filePath, String requestUrl) {
            this.context = context;
            this.filePath = filePath;
            this.requestUrl = requestUrl;
        }

        @Override
        protected void onPreExecute() {
            upload_image_progress_tv.setText("正在上传(" + (i + 1) + "/" + fileList.size() + ")");
        }

        @Override
        protected String doInBackground(String... params) {
            String serverResponse = null;
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(requestUrl);

            try {
                CustomMultipartEntity multipartContent = new CustomMultipartEntity(
                        new CustomMultipartEntity.ProgressListener() {
                            @Override
                            public void transferred(long num) {
                                publishProgress((int) ((num / (float) totalSize) * 100));
                            }
                        });

                // 使用FileBody上传图片
                multipartContent.addPart("value", new FileBody(new File(filePath)));
                totalSize = multipartContent.getContentLength();
                // 上传
                httpPost.setEntity(multipartContent);
                HttpResponse response = httpClient.execute(httpPost, httpContext);
                serverResponse = EntityUtils.toString(response.getEntity());
            } catch (Exception e) {
                e.printStackTrace();
            }
            return serverResponse;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            imageView.setProgress((int) (progress[0]));
        }

        @Override
        protected void onPostExecute(String result) {
            System.out.println("result: " + result);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(result.toString());
                String status = jsonObject.get("status").toString();
                if (status.equals("1")) {
                    String url = jsonObject.get("url").toString();
                    sburl.append(url);
                    sburl.append("#");

                    i++;
                    if (i < fileList.size()) {
                        upload();
                    } else {
                        doSubmit();
                    }
                } else {
                    Toast.makeText(MyLivingDetailActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onCancelled() {
            System.out.println("cancle");
        }

    }

    private void deleteImg() {
        for (int i=0;i<fileList.size();i++) {
            if (fileList.get(i).exists()) {
                fileList.get(i).delete();
            }
        }
    }

    private void doSubmit() {

        resetSize();

        httpUtils = new HttpUtils();
        params = new RequestParams();
        params.addBodyParameter("liveId", mylivingbeaninfo.getId());
        params.addBodyParameter("messageType", "1");
        params.addBodyParameter("isTitle", "0");
        params.addBodyParameter("widthHeight", sbwh.toString());
        params.addBodyParameter("message", sburl.toString());
        String urlmylivingadd = ServerURL.httpUrl + ServerURL.mylivingadd;
        httpUtils.send(HttpRequest.HttpMethod.POST, urlmylivingadd, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.d("wei", "发布图片成功" + responseInfo.result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(responseInfo.result.toString());
                    String status = jsonObject.get("status").toString();
                    if (status.equals("1")) {
                        dialog.dismiss();
                        getMylivingDetail(true);
                    }
                    //deleteImg();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d("wei", "发布内容失败" + msg);
            }
        });
    }


    private void resetSize() {
        sbwh = new StringBuilder();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        for (int i = 0; i < fileList.size(); i++) {
            Bitmap btemp = BitmapFactory.decodeFile(fileList.get(i).getPath(), options);
            sbwh.append("" + options.outWidth + "*" + options.outHeight);
            sbwh.append("#");
        }
        Log.d("wei", "图片宽高:" + sbwh.toString());
    }

}
